package com.laundry.user.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.laundry.user.databinding.FragmentHomeBinding
import com.laundry.user.ui.home.adapter.ServiceCategoryAdapter
import com.laundry.user.ui.home.adapter.RecommendedServiceAdapter
import com.laundry.user.ui.home.adapter.PromotedServiceAdapter
import com.laundry.user.ui.main.MainActivity
import com.laundry.user.utils.ViewUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeFragment : Fragment() {
    
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: HomeViewModel by viewModels()
    
    private lateinit var categoryAdapter: ServiceCategoryAdapter
    private lateinit var promotedAdapter: PromotedServiceAdapter
    private lateinit var recommendedAdapter: RecommendedServiceAdapter
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initViews()
        setupRecyclerViews()
        observeViewModel()
        loadData()
    }
    
    private fun initViews() {
        // 设置搜索框点击事件
        binding.searchBar.setOnClickListener {
            navigateToSearch()
        }
        
        // 设置位置点击事件
        binding.locationLayout.setOnClickListener {
            (activity as? MainActivity)?.requestLocationUpdate()
        }
        
        // 设置刷新事件
        binding.swipeRefreshLayout.setOnRefreshListener {
            refreshData()
        }
        
        // 设置扫码按钮
        binding.scanButton.setOnClickListener {
            // 打开扫码功能
            navigateToScan()
        }
        
        // 设置消息按钮
        binding.messageButton.setOnClickListener {
            navigateToMessages()
        }
    }
    
    private fun setupRecyclerViews() {
        // 服务分类
        categoryAdapter = ServiceCategoryAdapter { category ->
            navigateToCategory(category.id)
        }
        binding.categoryRecyclerView.apply {
            layoutManager = GridLayoutManager(context, 4)
            adapter = categoryAdapter
        }
        
        // 推广服务
        promotedAdapter = PromotedServiceAdapter(
            onServiceClick = { service ->
                navigateToServiceDetail(service.id)
            },
            onMerchantClick = { merchant ->
                navigateToMerchantDetail(merchant.id)
            }
        )
        binding.promotedRecyclerView.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = promotedAdapter
        }
        
        // 推荐服务
        recommendedAdapter = RecommendedServiceAdapter(
            onServiceClick = { service ->
                navigateToServiceDetail(service.id)
            },
            onMerchantClick = { merchant ->
                navigateToMerchantDetail(merchant.id)
            },
            onFavoriteClick = { service ->
                viewModel.toggleFavorite(service.id)
            }
        )
        binding.recommendedRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = recommendedAdapter
        }
    }
    
    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                updateUI(state)
            }
        }
        
        lifecycleScope.launch {
            viewModel.events.collect { event ->
                handleEvent(event)
            }
        }
    }
    
    private fun updateUI(state: HomeUiState) {
        // 更新加载状态
        binding.swipeRefreshLayout.isRefreshing = state.isLoading
        
        // 更新分类数据
        if (state.categories.isNotEmpty()) {
            categoryAdapter.submitList(state.categories)
            binding.categorySection.visibility = View.VISIBLE
        } else {
            binding.categorySection.visibility = View.GONE
        }
        
        // 更新推广服务
        if (state.promotedServices.isNotEmpty()) {
            promotedAdapter.submitList(state.promotedServices)
            binding.promotedSection.visibility = View.VISIBLE
        } else {
            binding.promotedSection.visibility = View.GONE
        }
        
        // 更新推荐服务
        if (state.recommendedServices.isNotEmpty()) {
            recommendedAdapter.submitList(state.recommendedServices)
            binding.recommendedSection.visibility = View.VISIBLE
        } else {
            binding.recommendedSection.visibility = View.GONE
        }
        
        // 更新位置信息
        state.currentLocation?.let { location ->
            binding.locationText.text = location.address ?: "定位中..."
        }
        
        // 更新用户信息
        state.userProfile?.let { profile ->
            binding.greetingText.text = "你好，${profile.nickname}"
            // 加载用户头像
            ViewUtils.loadAvatar(binding.userAvatar, profile.avatar)
        }
        
        // 更新错误状态
        if (state.error != null) {
            showError(state.error)
        }
        
        // 更新空状态
        updateEmptyState(state)
    }
    
    private fun handleEvent(event: HomeEvent) {
        when (event) {
            is HomeEvent.ShowError -> {
                showError(event.message)
            }
            is HomeEvent.NavigateToLogin -> {
                navigateToLogin()
            }
            is HomeEvent.ShowLocationPermissionDialog -> {
                showLocationPermissionDialog()
            }
            is HomeEvent.FavoriteToggled -> {
                showFavoriteResult(event.isAdded, event.serviceName)
            }
        }
    }
    
    private fun loadData() {
        val location = (activity as? MainActivity)?.getCurrentLocation()
        viewModel.loadHomeData(
            latitude = location?.latitude,
            longitude = location?.longitude
        )
    }
    
    private fun refreshData() {
        val location = (activity as? MainActivity)?.getCurrentLocation()
        viewModel.refreshData(
            latitude = location?.latitude,
            longitude = location?.longitude
        )
    }
    
    private fun updateEmptyState(state: HomeUiState) {
        val isEmpty = state.categories.isEmpty() && 
                     state.promotedServices.isEmpty() && 
                     state.recommendedServices.isEmpty() &&
                     !state.isLoading
        
        if (isEmpty) {
            binding.emptyStateView.visibility = View.VISIBLE
            binding.contentScrollView.visibility = View.GONE
            
            binding.emptyStateView.setOnRetryClickListener {
                loadData()
            }
        } else {
            binding.emptyStateView.visibility = View.GONE
            binding.contentScrollView.visibility = View.VISIBLE
        }
    }
    
    private fun showError(message: String) {
        com.google.android.material.snackbar.Snackbar.make(
            binding.root,
            message,
            com.google.android.material.snackbar.Snackbar.LENGTH_LONG
        ).apply {
            setAction("重试") {
                loadData()
            }
            show()
        }
    }
    
    private fun showFavoriteResult(isAdded: Boolean, serviceName: String) {
        val message = if (isAdded) "已添加到收藏" else "已取消收藏"
        com.google.android.material.snackbar.Snackbar.make(
            binding.root,
            message,
            com.google.android.material.snackbar.Snackbar.LENGTH_SHORT
        ).show()
    }
    
    private fun showLocationPermissionDialog() {
        // 显示位置权限对话框
        com.laundry.user.utils.PermissionUtils.showLocationPermissionDialog(requireContext()) {
            (activity as? MainActivity)?.requestLocationUpdate()
        }
    }
    
    // 导航方法
    private fun navigateToSearch() {
        val intent = android.content.Intent(context, com.laundry.user.ui.search.SearchActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToCategory(categoryId: String) {
        val intent = android.content.Intent(context, com.laundry.user.ui.category.CategoryActivity::class.java)
        intent.putExtra("category_id", categoryId)
        startActivity(intent)
    }
    
    private fun navigateToServiceDetail(serviceId: String) {
        val intent = android.content.Intent(context, com.laundry.user.ui.service.ServiceDetailActivity::class.java)
        intent.putExtra("service_id", serviceId)
        startActivity(intent)
    }
    
    private fun navigateToMerchantDetail(merchantId: String) {
        val intent = android.content.Intent(context, com.laundry.user.ui.merchant.MerchantDetailActivity::class.java)
        intent.putExtra("merchant_id", merchantId)
        startActivity(intent)
    }
    
    private fun navigateToScan() {
        val intent = android.content.Intent(context, com.laundry.user.ui.scan.ScanActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToMessages() {
        val intent = android.content.Intent(context, com.laundry.user.ui.message.MessageActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToLogin() {
        val intent = android.content.Intent(context, com.laundry.user.ui.auth.LoginActivity::class.java)
        startActivity(intent)
    }
    
    override fun onResume() {
        super.onResume()
        // 刷新数据
        if (viewModel.shouldRefreshData()) {
            refreshData()
        }
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

// UI状态数据类
data class HomeUiState(
    val isLoading: Boolean = false,
    val categories: List<com.laundry.user.data.model.ServiceCategory> = emptyList(),
    val promotedServices: List<com.laundry.user.data.model.Service> = emptyList(),
    val recommendedServices: List<com.laundry.user.data.model.Service> = emptyList(),
    val currentLocation: com.laundry.user.data.model.Location? = null,
    val userProfile: com.laundry.user.data.model.UserProfile? = null,
    val error: String? = null
)

// 事件数据类
sealed class HomeEvent {
    data class ShowError(val message: String) : HomeEvent()
    object NavigateToLogin : HomeEvent()
    object ShowLocationPermissionDialog : HomeEvent()
    data class FavoriteToggled(val isAdded: Boolean, val serviceName: String) : HomeEvent()
}
